package club.jdiy.admin.ueditor.upload;

import club.jdiy.admin.ueditor.PathFormat;
import club.jdiy.admin.ueditor.define.AppInfo;
import club.jdiy.admin.ueditor.define.BaseState;
import club.jdiy.admin.ueditor.define.FileType;
import club.jdiy.admin.ueditor.define.State;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import club.jdiy.core.AppContext;
import club.jdiy.core.storage.Store;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;

public class BinaryUploader {

	public static State save(AppContext context, HttpServletRequest request,
							 Map<String, Object> conf) {
		//FileItemStream fileStream = null;
		boolean isAjaxUpload = context.getRequest().getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(context.getRequest())) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());

        if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }
		try {

			MultipartFile mf = ((MultipartRequest)request).getFile(conf.get("fieldName").toString());

			/*FileItemIterator iterator = upload.getItemIterator(request);

			while (iterator.hasNext()) {
				fileStream = iterator.next();

				if (!fileStream.isFormField())
					break;
				fileStream = null;
			}
*/
			if (mf == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			String originFileName = mf.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0,
					originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = (Long) conf.get("maxSize");

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			savePath = PathFormat.parse(savePath, originFileName);

			String physicalPath = conf.get("rootPath") + savePath;

			/*InputStream is = mf.getInputStream();
			State storageState = StorageManager.saveFileByInputStream(is,
					physicalPath, maxSize);
			is.close();*/

			Store store =context.getStore("ueditor_img","v1");
			String upurl = store.put(mf,originFileName);

			State storageState = new BaseState(true);
			storageState.putInfo( "size", 100 );
			storageState.putInfo( "title", originFileName);

			if (storageState.isSuccess()) {
				storageState.putInfo("url", upurl/*PathFormat.format(savePath)*/);
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}

			return storageState;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
